package com.shixihub;

import com.shixihub.data.AppDataEntity;
import com.shixihub.data.AppDataManager;
import com.shixihub.data.HostListEntity;
import com.shixihub.ssh.JumpHostHelper;
import com.shixihub.view.HostEntity;
import com.shixihub.view.HostEntityClone;
import com.shixihub.view.HostManagerController;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

public class AppController implements Initializable {
    public static final String COM_SHIXIHUB_VIEW_HOST_MANAGER_FXML = "/com/shixihub/view/HostManager.fxml";
    public TreeView<HostEntity> treeViewHost = new TreeView<>();
    TreeItem<HostEntity> root;
    public TreeView localFileExplorer = new TreeView();
    public TreeView remoteFileExplorer = new TreeView();

    AppDataManager appDataManager = new AppDataManager();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        final HostEntity hostEntity = new HostEntity();
        hostEntity.setName("我的资产");
        treeViewHost.setShowRoot(false);
        root = new TreeItem(hostEntity);
        treeViewHost.setRoot(root);
        treeViewHost.setCellFactory(param -> new TreeCell<HostEntity>() {
            @Override
            protected void updateItem(HostEntity item, boolean empty) {
                super.updateItem(item, empty);
                setText((empty || item == null) ? null : item.getName());
            }
        });
        // 恢复主机列表
        Platform.runLater(() -> restoreTargetHosts());
    }

    public void onCreateHost(ActionEvent actionEvent) throws IOException {
        // 读取弹窗的界面布局
        HostManagerController hostManagerController = null;
        BorderPane borderPane = null;
        try {
            final FXMLLoader fxmlLoader = new FXMLLoader(Objects.requireNonNull(HostManagerController.class
                    .getResource(COM_SHIXIHUB_VIEW_HOST_MANAGER_FXML)));
            borderPane = fxmlLoader.load();
            hostManagerController = fxmlLoader.getController();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 弹窗界面
        final Dialog<Object> objectDialog = new Dialog<>();
        objectDialog.getDialogPane().setContent(borderPane);
        final ButtonType buttonTypeSave = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        final ButtonType buttonTypeCancelClose = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
        objectDialog.getDialogPane().getButtonTypes().addAll(buttonTypeSave, buttonTypeCancelClose);
        HostManagerController finalHostManagerController = hostManagerController;
        objectDialog.showAndWait().ifPresent(responseButtonType -> {
            if (responseButtonType == buttonTypeSave) {
                final ObservableList<HostEntity> observableListHost = finalHostManagerController.observableListHost;
                if(observableListHost.isEmpty()){
                    return;
                }
                final TreeItem<HostEntity> targetHost = new TreeItem<>(observableListHost
                        .remove(observableListHost.size() - 1));
                final TreeItem<HostEntity> root = treeViewHost.getRoot();
                root.getChildren().add(targetHost);
                observableListHost.forEach(hostEntityClone -> targetHost.getChildren().add(new TreeItem<>(hostEntityClone)));
                System.out.printf("新增条数%s\n:", observableListHost.size());

                // 保存服务
                Platform.runLater(() -> saveTargetHosts());
            } else if (responseButtonType == buttonTypeCancelClose) {
                System.out.println("取消");
            }
        });
    }
    public String saveTargetHosts() {
        final AppDataEntity appData = new AppDataEntity();

        final ObservableList<TreeItem<HostEntity>> targetHosts = treeViewHost.getRoot().getChildren();
        // 封装目标主机和代理主机
        targetHosts.forEach(hostEntityTreeItem -> {
            final HostEntityClone targetHost = hostEntityTreeItem.getValue().toCloneEntity();
            final HostListEntity e = new HostListEntity();
            e.targetHost = targetHost;
            hostEntityTreeItem.getChildren().forEach(hostEntityTreeItem1 -> {
                final HostEntityClone proxyHost = hostEntityTreeItem1.getValue().toCloneEntity();
                e.proxyHosts.add(proxyHost);
            });
            appData.targetHostList.add(e);
            appDataManager.setAppDataEntity(appData);
        });

        // 落盘
        return appDataManager.store(appData);
    }

    /**
     * 恢复左侧主机列表
     * @return
     */
    public String restoreTargetHosts() {
        final AppDataEntity restore = appDataManager.restore();
        restore.targetHostList.forEach(hostListEntity -> {
            final TreeItem<HostEntity> targetHostTreeItem = new TreeItem<>(HostEntity.from(hostListEntity.targetHost));
            treeViewHost.getRoot().getChildren().add(targetHostTreeItem);
            for (HostEntityClone proxyHost : hostListEntity.proxyHosts) {
                targetHostTreeItem.getChildren().add(new TreeItem<>(HostEntity.from(proxyHost)));
            }
        });
        return null;
    }

    /**
     * 连接目标主机
     * @param actionEvent
     */
    public void onConn(ActionEvent actionEvent) {
        final TreeItem<HostEntity> selectedItem = treeViewHost.getSelectionModel().getSelectedItem();
        final HostEntity value = selectedItem.getValue();
        System.out.println("连接目标主机：" + value.getIpAddress());
        final List<HostEntity> proxyHosts = selectedItem.getChildren().stream().map(hostEntityTreeItem -> hostEntityTreeItem.getValue()).collect(Collectors.toList());
        JumpHostHelper.conn(value,proxyHosts);

    }
}
